<script lang="ts" setup>
import type { Ref } from 'vue';

import type { DataFormOptionsProps } from '#/components/data-form/types';

import { ref } from 'vue';

import { getMenuTree, getRoleDetails } from '#/api';
import { DataForm } from '#/components/data-form';
import { useForm } from '#/views/system/role/data';

const dataFormRef = ref<InstanceType<typeof DataForm>>();
const menuTreeRef = ref();
const menuTreeData = ref<any[]>([]);

const { fields, rules } = useForm();

const onBeforeSubmit = (form: Ref<Record<string, any>>) => {
    const checked = menuTreeRef.value?.getCheckedNodes(false);
    const halfChecked = menuTreeRef.value?.getHalfCheckedNodes();
    form.value.menus = [...checked, ...halfChecked];
    return true;
};

const open = (options: DataFormOptionsProps) => {
    const roles = Array.isArray(options.data?.checks) ? options.data.checks.map((item) => item.id) : options.data?.id;

    Promise.all([getMenuTree(), getRoleDetails(roles)]).then(([v1, v2]) => {
        // 菜单数据
        menuTreeData.value = v1.data;
        // 已选中的菜单数据
        const menus: any[] = [];
        v2.data?.reduce((pre: any, cur: any) => {
            if (cur && cur.menus?.length > 0) {
                pre.push(...cur.menus);
            }
            return pre;
        }, menus);
        Object.assign(options.data!!, { menus });
        // 打开弹窗
        dataFormRef.value?.open(options);
    });
};

defineExpose({ open });
</script>

<template>
    <DataForm ref="dataFormRef" :before-submit="onBeforeSubmit" :fields="fields" :rules="rules" api="/system/role" title="角色">
        <template #checks="{ label, form }">
            <el-form-item :label="label" prop="checks" v-show="form.checks">
                <el-select v-model="form.checks" value-key="id" disabled multiple>
                    <el-option v-for="item in form.checks" :key="item.id" :label="item.name" :value="item" />
                </el-select>
            </el-form-item>
        </template>
        <template #menus="{ form }">
            <el-tree
                ref="menuTreeRef"
                :accordion="true"
                :check-strictly="true"
                :check-on-click-node="true"
                :data="menuTreeData"
                :default-checked-keys="form.menus.map((item: any) => item.id)"
                :expand-on-click-node="true"
                :show-checkbox="true"
                node-key="id"
                style="height: 30vh; width: 100%; overflow: auto"
            >
                <template #default="{ data }">
                    <span v-if="data.perms">{{ data.title }}&nbsp;(权限标识:{{ data.perms }})</span>
                    <span v-else>{{ data.title }}</span>
                </template>
            </el-tree>
        </template>
    </DataForm>
</template>
